import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'

// 引入页面组件(路由懒加载)
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Dashboard = () => import('@/views/dashboard')
const Article = () => import('@/views/article')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      redirect: '/dashboard',
      component: Layout,
      children: [
        { path: 'dashboard', component: Dashboard },
        { path: 'article', component: Article }
      ]
    }
  ]
})

// 设置路由全局前置守卫
router.beforeEach((to, from, next) => {
  // 1. 获取token 和 设置白名单
  const token = store.state.user.token
  const whiteList = ['/login']
  // 2. 判断是否有token
  if (token) {
    // 2.1 有token, 直接放行
    next()
  } else {
    // 2.2 没有token
    if (whiteList.includes(to.path)) {
      // 2.2.1 在白名单中, 直接放行
      next()
    } else {
      // 2.2.2 不在白名单中, 拦截到登录页面
      next('/login')
    }
  }
})

export default router
